from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import check_password
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny

from user.serializers import UserSerializer, RoleSerializer, ClazzSerializer
from user.models import User, Role, Clazz


current_user = get_user_model()


class UserViewSet(viewsets.GenericViewSet):

    queryset = User.objects.filter(is_delete=False)

    serializer_class = UserSerializer

    # 放开指定接口权限
    def get_permissions(self):
        if self.action in ['create', 'find_clazz_list']:
            return [AllowAny()]
        return super().get_permissions()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    @action(methods=['GET'], detail=False, url_path='find_role_class_list', url_name='find_role_class_list')
    def find_role_class_list(self, request, *args, **kwargs):

        # 查询所有角色信息
        roles_queryset = Role.objects.filter(is_delete=False, state=True)

        # 查询所有班级信息
        class_queryset = Clazz.objects.filter(is_delete=False, state=True)

        roles_serializer = RoleSerializer(roles_queryset, many=True, fields=['id', 'name'])

        class_serializer = ClazzSerializer(class_queryset, many=True, fields=['id', 'name'])

        data = {
            'roleList': roles_serializer.data,
            'clazzList': class_serializer.data
        }

        return Response(data, status=status.HTTP_200_OK)

    # 查询所有角色信息
    @action(['GET'], detail=False, url_path='find_user_list', url_name='find_user_list')
    def find_user_list(self, request, *args, **kwargs):

        users = User.objects.filter(is_delete=False, is_active=True)
        users_serializer = UserSerializer(users, many=True)
        return Response(users_serializer.data, status=status.HTTP_200_OK)

    @action(['GET'], detail=False, url_path='find_clazz_list', url_name='find_clazz_list')
    def find_clazz_list(self, request, *args, **kwargs):
        clazz_list = Clazz.objects.filter(is_delete=False)
        clazz_serializer = ClazzSerializer(clazz_list, many=True)
        return Response(clazz_serializer.data, status=status.HTTP_200_OK)

    # 修改班级
    @action(['PUT'], detail=False, url_path='switch_clazz', url_name='switch_clazz')
    def switch_clazz(self, request, *args, **kwargs):
        current_user.objects.filter(id=request.user.id).update(
            clazz_id=request.data.get('clazz_id')
        )
        return Response({'message': '切换成功'})

    # 修改密码
    @action(['PUT'], detail=False, url_path='change_password', url_name='change_password')
    def change_password(self, request, *args, **kwargs):
        user_id = request.user.id
        old_password = request.data.get('oldPassword')
        new_password = request.data.get('password')
        confirm_password = request.data.get('password2')

        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({"detail": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)

        # 校验旧密码是否正确
        if not check_password(old_password, user.password):
            return Response({'detail': '原密码错误'}, status=status.HTTP_400_BAD_REQUEST)

        # 检查新密码是否为空
        if not new_password:
            return Response({'detail': '新密码不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        if new_password != confirm_password:
            return Response({'detail': '新密码与确认密码不一致'}, status=status.HTTP_400_BAD_REQUEST)

        # 修改密码
        user.set_password(new_password)
        user.save()
        return Response({'message': '密码修改成功'}, status=status.HTTP_200_OK)

    # 重置密码
    @action(['PUT'], detail=False, url_path='reset_password_active', url_name='reset_password_active')
    def reset_password_active(self, request, *args, **kwargs):
        stu_id = request.data.get('id')
        sign = request.data.get('sign')

        if not stu_id:
            return Response({'error': '缺少用户ID'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(id=stu_id)
        except User.DoesNotExist:
            return Response({'error': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)

        if sign == '123456':
            print("重置密码")
            user.set_password('123456')  # 重置密码为123456（加密）
            user.save()
            return Response({'message': '密码已重置为123456'}, status=status.HTTP_200_OK)

        elif sign == '0':
            print("禁用账号")
            user.is_active = False  # 禁用账号
            user.save()
            return Response({'message': '用户已被禁用'}, status=status.HTTP_200_OK)

        else:
            return Response({'error': 'sign 值有误'}, status=status.HTTP_400_BAD_REQUEST)

